'''构建神经网络，
可视化准确率和损失
'''
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import data_pre_process
from my_util import  label_alpha_to_number
from my_util import  num_to_alpha_dict
from my_util import  show_verification_code
import shutil
import os
import cv2
import pathlib

train_image=data_pre_process.get_train_img()
train_label=data_pre_process.get_train_label()
train_label=label_alpha_to_number(train_label)



def build_model():
    '''
    构建模型
    :return: model  模型
    '''
    model = tf.keras.Sequential()
    model.add(tf.keras.layers.Flatten(input_shape=(25, 25,3)))
    model.add(tf.keras.layers.Dense(256, activation='relu'))
    model.add(tf.keras.layers.Dense(36, activation='softmax'))
    print(model.summary())
    return model

def train(model):
    train_label_onehot=tf.keras.utils.to_categorical(train_label)
    model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc'])
    history = model.fit(train_image, train_label_onehot, epochs=100)
    model.save('my_third_model.h5')
    plt.plot(history.epoch, history.history.get('loss'))
    plt.plot(history.epoch, history.history.get('acc'))
    plt.legend(labels=['损失', '准确率', ], loc='best')
    return history

def predict():
    '''
    给一张图片预测验证码
    :return: 验证码字符串
    '''
    data_pre_process.predict_image_segmentation()
    model=tf.keras.models.load_model('my_second_model.h5')
    predict_img=data_pre_process.get_predict_img()
    predict = model.predict(predict_img)
    code_list=[]
    for i in  range(len(predict)):
        if np.argmax(predict[i])>9:
            code=str(num_to_alpha_dict[str(np.argmax(predict[i]))])
            code_list.append(code)
        else:
            code = str(np.argmax(predict[i]))
            code_list.append(code)
    print("验证码为:",show_verification_code(code_list))        #杨广瑶
    shutil.rmtree(r"D:\dataset\predict_segmented_image")  # 删除文件夹
    if not os.path.exists(r"D:\dataset\predict_segmented_image"):
        os.makedirs(r"D:\dataset\predict_segmented_image")
    shutil.rmtree(r"C:\Users\14121\Desktop\predict")  # 删除文件夹
    if not os.path.exists(r"C:\Users\14121\Desktop\predict"):
        os.makedirs(r"C:\Users\14121\Desktop\predict")
    return show_verification_code(code_list)

def show_predict_accuracy():
    '''
    显示测试的准确率
    :return:
    '''
    data_root=pathlib.Path(r"C:\Users\14121\Desktop\can")
    right_number=0
    all_number=0
    for item in data_root.iterdir():
        all_number+=1
        predict_image=cv2.imread(str(item))
        image_rel = pathlib.Path(item).relative_to(data_root)  # 计算相对路径
        cv2.imwrite(r"C:\Users\14121\Desktop\predict\{}.jpg".format(str(image_rel)[:6]),predict_image)
        if str(image_rel)[:6]==predict():
            right_number+=1
    print("预测准确率",right_number/all_number)



if __name__=='__main__':
    pass
    #train(build_model())
    # plt.rcParams['font.family'] = ['sans-serif']  # 设置字体
    # plt.rcParams['font.sans-serif'] = ['SimHei']
    # plt.show()
    #predict()
    #show_predict_accuracy()